import { Button, message, Form, Input, type FormProps, Modal, InputNumber, Table } from "antd"
import "./index.scss"
import { useEffect, useState } from "react";
import { getColumns } from "./columns";
// import { getData } from "../../api"
import { getMall, deleteMall, addMall, editMall } from "@/realApi";
import type { MallProp } from "../../realApi/types"

interface SearchProps {
  keyword: string
}

enum OperationType {
  Add,
  Edit
}

export default function Mall () {
  // [消息提示的实例, 渲染消息提示的react组件]
  const [messageApi, contextHolder] = message.useMessage()

  // 弹窗显示隐藏
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)

  // 新增/编辑
  const [modalType, setModalType] = useState<OperationType>(OperationType.Add)

  // 表格数据
  const [tableData, setTableData] = useState<Record<string, any>[]>([])

  // 创建form实例
  const [form] = Form.useForm()

  const handleAdd = () => {
    setIsModalOpen(true)
    setModalType(OperationType.Add)
    // messageApi.success({
    //   content: "新增"
    // })
  }

  const handleFinish: FormProps<SearchProps>['onFinish'] = (search) => {
    getData()
  }

  const handleModalFinish: FormProps<MallProp>['onFinish'] = (values) => {
    const service = values.id ? editMall : addMall
    console.log('service :>> ', service);
    service(values).then(res => {
      if (res.status === 200) {
        messageApi.success(`${values.id ? '编辑' : '新增'}商品成功`)
        setIsModalOpen(false)
        form.resetFields()
        getData()
      }
    }).catch(err => {
      messageApi.error(err.response.data.message)
    })
  }

  const handleOk = () => {
    form.submit()
  }

  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields()
  }

  const handleEdit = (rowData) => {
    setIsModalOpen(true)
    setModalType(OperationType.Edit)
    form.setFieldsValue(rowData)
  }

  const handleDelete = (rowData) => {
    const id = rowData.id
    deleteMall(id).then(res => {
      if (res.status === 200) {
        messageApi.success(res.data.message)
        getData()
      }
    }).catch(err => {
      messageApi.error(err.response.data.message)
    })
  }

  const getData = function () {
    getMall().then(({ data }) => {
      setTableData(data)
    })
  }

  //  表格头部属性
  const columns = getColumns(handleEdit, handleDelete)

  useEffect(() => {
    getData()
  }, [])

  return (
    <>
      {contextHolder}

      <div className="mall">
        <div className="flex-box space-between">
          <Form className="mall-form" layout="inline" onFinish={handleFinish}>
            <Form.Item className="search-input" name="keyword">
              <Input placeholder="请输入商品名称"></Input>
            </Form.Item>
            <Form.Item className="search-bar-buttons">
              <Button htmlType="button" type="primary" onClick={handleAdd}>新增</Button>
              <Button className="search-button" htmlType="submit" type="primary">搜索</Button>
            </Form.Item>
          </Form>
        </div>
      </div>

      <Table bordered style={{ margin: "0 16px" }} columns={columns} dataSource={tableData} rowKey={'id'} pagination={{ defaultPageSize: 3 }}></Table>

      <Modal open={isModalOpen} centered maskClosable={false} title={modalType === OperationType.Add ? "新增商品" : "编辑商品"} onOk={handleOk} onCancel={handleCancel} okText="确定" cancelText="取消">
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} labelAlign="left" onFinish={handleModalFinish}>
          {modalType === OperationType.Edit && <Form.Item name="id" hidden> <Input></Input> </Form.Item>}

          <Form.Item label="商品名称" name="name" rules={[{ required: true, message: "请输入商品名称" }, { pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: "不支持数字，特殊字符或空格！" }]}>
            <Input placeholder="请输入商品名称"></Input>
          </Form.Item>

          <Form.Item label="商品价格" name="price" rules={[{ required: true, message: "请输入商品价格" }, { type: "number", message: "商品价格必须是数字" }]}>
            <InputNumber style={{ width: "8vw" }} placeholder="请输入商品价格"></InputNumber>
          </Form.Item>

          <Form.Item label="商品图片" name="pic" rules={[{ required: true, message: "请输入上屏图片链接" }]}>
            <Input placeholder="请输入商品图片链接"></Input>
          </Form.Item>

          <Form.Item label="商品数量" name="count" rules={[{ required: true, message: "请输入商品数量" }, { type: "number", message: "商品数量必须是数字" }]}>
            <InputNumber style={{ width: "8vw" }} placeholder="请输入商品数量"></InputNumber>
          </Form.Item>

          <Form.Item label="商品描述" name="description" rules={[{ required: true, message: "请输入商品描述" }]}>
            <Input.TextArea placeholder="请输入商品描述"></Input.TextArea>
          </Form.Item>
        </Form>
      </Modal >
    </>
  )
}
